var websocket = null;
$(function () {
	//百度富文本框内容为空
    $(".w-e-text").html("");
    //快捷键 按 enter键
    $(document).keydown(function(event){
        if(event.keyCode==13){
            send();
        }
    });
})
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
    // websocket = new WebSocket("ws://192.144.184.199:8080/websocket");
	//websocket自建服务器的地址
     websocket = new WebSocket("ws://localhost:8080/TeaCulture/websocket");

}
else{
    alert('Not support websocket')
}
/**
 *
 * 获取当前时间
 */
function getNow(s) {
    return s < 10 ? '0' + s: s;
}
//连接发生错误的回调方法
websocket.onerror = function(){
    setMessageInnerHTML("error");
};

//连接成功建立的回调方法
websocket.onopen = function(event){
    setMessageInnerHTML("open");
}

//接收到消息的回调方法
websocket.onmessage = function(event){
    setMessageInnerHTML(event.data);
}

//连接关闭的回调方法
websocket.onclose = function(){
    setMessageInnerHTML("close");
}

//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function(){
    websocket.close();
}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
    document.getElementById('message').innerHTML += innerHTML + '<br/>';
    $(".container").scrollTop($(".container")[0].scrollHeight);

}

//关闭连接
function closeWebSocket(){
    websocket.close();
}
//字符长度计算
function getStrLength(str) {
var cArr = str.match(/[^\x00-\xff]/ig);
return str.length + (cArr == null ? 0 : cArr.length);
}


//发送消息
function send(){
    var editor = $(".w-e-text").html();
    console.log(editor);
    if(editor == '' || editor == null){
        layer.msg("请输入发送内容！", {icon: 5});
        return false;
    }
    var myDate = new Date();
    //获取当前年
    var year=myDate.getFullYear();
    //获取当前月
    var month=myDate.getMonth()+1;
    //获取当前日
    var date=myDate.getDate();
    var h=myDate.getHours();       //获取当前小时数(0-23)
    var m=myDate.getMinutes();     //获取当前分钟数(0-59)
    var s=myDate.getSeconds();

    var now=year+'-'+getNow(month)+"-"+getNow(date)+" "+getNow(h)+':'+getNow(m)+":"+getNow(s);
    websocket.send("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+now);
    var message = $("#nickname").val()+":"+editor;
    console.log(getStrLength(message));
    websocket.send(message);
    $(".w-e-text").html("");
}